# crud/sys_table_mapping.py
from sqlalchemy.orm import Session
from src.models.sys_table_mapping import SysTableMapping
from src.schemas.sys_table_mapping import SysTableMappingCreate, SysTableMappingUpdate


def create_table_mapping(db: Session, table_mapping: SysTableMappingCreate):
    """
    创建表匹配记录。
    """
    db_table_mapping = SysTableMapping(**table_mapping.dict())
    db.add(db_table_mapping)
    db.commit()
    db.refresh(db_table_mapping)
    return db_table_mapping


def create_table_mappings(db: Session, table_mappings: list[SysTableMappingCreate]):
    """
    批量创建表匹配记录。
    """
    db_table_mappings = [SysTableMapping(**tm.dict()) for tm in table_mappings]
    try:
        db.add_all(db_table_mappings)
        db.commit()
        for db_table_mapping in db_table_mappings:
            db.refresh(db_table_mapping)
        return db_table_mappings
    except Exception as e:
        db.rollback()
        raise e


def get_table_mapping(db: Session, mapping_id: str):
    """
    根据 ID 获取表匹配记录。
    """
    return db.query(SysTableMapping).filter(SysTableMapping.id == mapping_id).first()


def get_table_mappings(db: Session, skip: int = 0, limit: int = 100):
    """
    获取表匹配记录列表。
    """
    return db.query(SysTableMapping).offset(skip).limit(limit).all()


def update_table_mapping(db: Session, mapping_id: str, table_mapping: SysTableMappingUpdate):
    """
    更新表匹配记录。
    """
    db_table_mapping = db.query(SysTableMapping).filter(SysTableMapping.id == mapping_id).first()
    if db_table_mapping is None:
        return None
    update_data = table_mapping.dict(exclude_unset=True)
    for key, value in update_data.items():
        setattr(db_table_mapping, key, value)
    db.commit()
    db.refresh(db_table_mapping)
    return db_table_mapping


def delete_table_mapping(db: Session, mapping_id: str):
    """
    删除表匹配记录。
    """
    db_table_mapping = db.query(SysTableMapping).filter(SysTableMapping.id == mapping_id).first()
    if db_table_mapping is None:
        return None
    db.delete(db_table_mapping)
    db.commit()
    return db_table_mapping
